package benny_driving_ser.dao.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;

import benny_driving_ser.dao.TaximeterDao;
import benny_driving_ser.entity.Taximeter;
import benny_driving_ser.util.DBUtil;
import benny_driving_ser.util.FormatUtil;
import benny_driving_ser.util.SendSMSUtil;

public class TaximeterDaoImpl implements TaximeterDao {
	String sql_queryByDriid;
	private static final int KEY = 54321;
	private static final String SMS_URL = "";
	private static final String SMS_TM_CONTENT = "http://www.4008200972.com/w/j.php&id="
			+ SMS_URL;
	private static final String SMS_BILING_CONTENT = "http://www.4008200972.com/w/p.php&id=";

	private TaximeterDaoImpl() {
		sql_queryByDriid = "SELECT t_djpd.state,t_djpd.id,t_hy.sjh FROM t_djpd INNER JOIN t_hy WHERE t_djpd.user_id = t_hy.id AND t_djpd.state < 6 AND t_djpd.dri_id = ?";
	}

	private static class TaximeterDaoImplHolder {
		private static TaximeterDaoImpl instance = new TaximeterDaoImpl();
	}

	public static TaximeterDaoImpl getInstance() {
		return TaximeterDaoImplHolder.instance;
	}

	public long ctrlTaximeterStart(int driid, String startPos) {
		String sql_update_2to3 = "UPDATE t_djpd SET sjqd = ?,state = 3,start_time=? WHERE dri_id = ? AND t_djpd.state = 2";
		String sql_update_4to3 = "UPDATE t_djpd SET state = 3 WHERE dri_id = ? AND t_djpd.state = 4";
		Connection con = DBUtil.getInstance().openConnection();
		try {
			con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			con.setAutoCommit(false);
			PreparedStatement ps = con.prepareStatement(sql_queryByDriid);
			ps.setInt(1, driid);
			ResultSet rs = ps.executeQuery();
			int state, formId;
			String userTel, formIdHex;
			if (rs.next()) {
				formId = rs.getInt(2);
				userTel = rs.getString(3);
				formIdHex = encryption(formId);
				if ((state = rs.getInt(1)) != 3) {
					ps.clearBatch();
					if (state == 2) {
						ps = con.prepareStatement(sql_update_2to3);
						ps.setString(1, startPos);
						ps.setString(2, FormatUtil.getTimeFormatNow());
						ps.setInt(3, driid);
					}
					if (state == 4) {
						ps = con.prepareStatement(sql_update_4to3);
						ps.setInt(1, driid);

					}
					if (ps.executeUpdate() == 1) {
						if (state == 2) {
							if (SendSMSUtil.getInstance().sendSMS(
									userTel.trim(),
									URLEncoder.encode("您的代驾服务已开始计费", "gbk")))
								System.out
										.println("send message 您的代驾服务已开始计费，监控计费登录"
												+ SMS_TM_CONTENT
												+ formIdHex
												+ userTel);
						}
						con.commit();
						return System.currentTimeMillis();
					}
					con.rollback();
					return 6;
				}
				con.rollback();
				return 5;
			}
			con.rollback();
			return 4;
		} catch (SQLException e) {
			e.printStackTrace();
			return 3;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();// gbk编码错误
			return 7;
		} finally {
			DBUtil.getInstance().closeConnection(con);
		}
	}

	public long ctrlTaximeterPause(int driid, String startPos) {
		String sql_update_2to4 = "UPDATE t_djpd SET sjqd = ?,state = 4,start_time = ? WHERE dri_id = ? AND t_djpd.state = 2";
		String sql_update_3to4 = "UPDATE t_djpd SET state = 4 WHERE dri_id = ? AND t_djpd.state = 3";
		Connection con = DBUtil.getInstance().openConnection();
		try {
			con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			con.setAutoCommit(false);
			PreparedStatement ps = con.prepareStatement(sql_queryByDriid);
			ps.setInt(1, driid);
			ResultSet rs = ps.executeQuery();
			int state, formId;
			String userTel, formIdHex;
			if (rs.next()) {
				formId = rs.getInt(2);
				userTel = rs.getString(3);
				formIdHex = encryption(formId);
				if ((state = rs.getInt(1)) != 4) {
					ps.clearBatch();
					if (state == 2 && null != startPos) {
						ps = con.prepareStatement(sql_update_2to4);
						ps.setString(1, startPos);
						ps.setString(2, FormatUtil.getTimeFormatNow());
						ps.setInt(3, driid);
					}
					if (state == 3) {
						ps = con.prepareStatement(sql_update_3to4);
						ps.setInt(1, driid);
					}
					
//					System.out.println("ps:"+ps.executeUpdate());
					if (ps.executeUpdate() == 1) {
						if (state == 2) {
							if (SendSMSUtil.getInstance().sendSMS(
									userTel.trim(),
									URLEncoder.encode("您的代驾服务已开始计费", "gbk")))
								System.out
										.println("send message 您的代驾服务已开始计费，监控计费登录"
												+ SMS_TM_CONTENT
												+ formIdHex
												+ userTel);
						}
						con.commit();
						return System.currentTimeMillis();
					}
					return 6;
				}
				return 5;
			}
			return 4;
		} catch (SQLException e) {
			e.printStackTrace();
			return 3;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();// gbk编码异常
			return 7;
		} finally {
			DBUtil.getInstance().closeConnection(con);
		}
	}

	public long ctrlTaximeterStop(int driid, String desPos, int opp) {
		String sql_update_3 = "UPDATE t_djpd,t_user SET t_djpd.sjzd = ?,"// 1
				+ "t_djpd.state = ?,"// 2
				+ "t_djpd.pay = ?,"// 3
				+ "t_user.ye= ? ,"// 4
				+ "t_user.state = ?,"// 5
				+ "t_djpd.end_time = ?,"// 6
				+ "t_djpd.ssfy = ?,"// 7
				+ "t_djpd.ksje = ?,"// 8
				+ "t_djpd.mdfy = ?"// 9
				+ " WHERE t_djpd.dri_id = t_user.id AND t_djpd.dri_id = ? " + // 10
				"AND t_djpd.state < 7 AND t_djpd.state > 2";
		String sql_update_4 = "UPDATE t_djpd,t_user SET t_djpd.sjzd = ?,t_djpd.state = ?,t_djpd.pay = ?,t_user.state = ?,t_djpd.end_time = ? WHERE t_djpd.dri_id = t_user.id AND t_djpd.dri_id = ?";
		String sql_query = "SELECT t_hy.sjh,"
				+ "t_djpd.total,"
				+ "t_user.ye,"
				+ "t_hy.id,"
				+ "t_user.dh,"
				+ "t_djpd.qd,"
				+ "t_djpd.zd,"
				+ "t_user.username, "
				+ "t_user.mdid, "
				+ "t_djpd.userid "
				+ "FROM t_hy,t_djpd,t_user WHERE t_hy.id = t_djpd.user_id AND t_djpd.dri_id = ? AND t_user.id = t_djpd.dri_id AND t_djpd.state < 6";
		String sql_update_pos = "UPDATE t_djpd SET t_djpd.qd = t_djpd.sjqd,t_djpd.zd = t_djpd.sjzd,t_djpd.yyrq = t_djpd.start_time WHERE t_djpd.id = ? AND t_djpd.state > 5";

		Connection con = DBUtil.getInstance().openConnection();
		try {
			con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			con.setAutoCommit(false);
			PreparedStatement ps1 = con.prepareStatement(sql_queryByDriid);// 用户手机号，订单金额，司机余额，用户id，司机手机号
			ps1.setInt(1, driid);
			ResultSet rs1 = ps1.executeQuery();
			int state, formId;
			String formIdHex;
			if (rs1.next()) {
				formId = rs1.getInt(2);// formId
				formIdHex = encryption(formId);
				if (((state = rs1.getInt(1)) == 3 || state == 4)) {
					System.out.println("0");
					int formid = rs1.getInt(2);// formid;
					PreparedStatement ps2 = con.prepareStatement(sql_query);
					System.out.println("--------------------------" + driid
							+ "------------------------------");
					ps2.setInt(1, driid);
					ResultSet rs2 = ps2.executeQuery();
					if (rs2.next()) {
						// int service = rs2.getInt(10);
						int mdid = rs2.getInt(9);
						String driJobNum = rs2.getString(8);
						String userTel = rs2.getString(1);
						double total = FormatUtil.getFormatDouble(0,
								Double.parseDouble(rs2.getString(2).trim()));
						double money = rs2.getDouble(3);
						int userid = rs2.getInt(4);
						String driTel = rs2.getString(5);
						double tax = FormatUtil.getFormatDouble(2, total
								* getTax(total));
						if (money < tax)
							return 7;
						switch (opp) {
						case 3:
							System.out.println("3");
							PreparedStatement ps3 = con
									.prepareStatement(sql_update_3);
							ps3 = con.prepareStatement(sql_update_3);
							ps3.setString(1, desPos);// 实际地址sjdz
							ps3.setInt(2, 7);// 状态state
							ps3.setInt(3, 0);// pay
							ps3.setDouble(4, money - tax);// ye
							ps3.setInt(5, 1);// user state
							ps3.setString(6, FormatUtil.getTimeFormatNow());// end
																			// time
							ps3.setDouble(7, total);// ssfy
							ps3.setDouble(8, tax);// ksje
							ps3.setString(9, getManageProfit(tax, mdid) + "");
							ps3.setInt(10, driid);// driid
							if (ps3.executeUpdate() != 0
									&& UtilDaoImpl.getInstance()
											.insertDriExpenseCalendar(con,
													driid, (-tax), 1, formid,
													driJobNum)
									&& UtilDaoImpl.getInstance()
											.insertUserExpenseCalendar(con,
													userid, -total, 1, formid)
									&& UtilDaoImpl.getInstance()
											.insertManagerCount(con, mdid,
											getManageProfit(tax, mdid))
									&& UtilDaoImpl
											.getInstance()
											.isServerSendOrder(con, tax, formId)
//									&& UtilDaoImpl.getInstance().cardInfoUpdate(formId, con)
									) {
								System.out.println("send message 本次代驾费用"
										+ total + "元,开票登陆: "
										+ SMS_BILING_CONTENT + formIdHex);
								SendSMSUtil.getInstance().sendSMS(
										userTel,
										URLEncoder.encode("本次代驾费用" + total
												+ "元", "gbk"));
								SendSMSUtil.getInstance().sendSMS(
										driTel,
										URLEncoder.encode("用户通过现金支付代驾费用"
												+ total + "元，您此次代驾扣税金额为" + tax
												+ "元", "gbk"));
								if (null == rs2.getString(6)
										&& null == rs2.getString(7)) {
									PreparedStatement mPs = con
											.prepareStatement(sql_update_pos);
									mPs.setInt(1, formid);
									if (mPs.executeUpdate() == 0)
										return 9;// 地址，日期更改失败
								}
								con.commit();
								return System.currentTimeMillis();
							}
							return 10;// 订单修改失败
						case 4:
							PreparedStatement ps4 = con
									.prepareStatement(sql_update_4);
							ps4.setString(1, desPos);
							ps4.setInt(2, 6);
							ps4.setInt(3, -1);
							ps4.setInt(4, 1);
							ps4.setString(5, FormatUtil.getTimeFormatNow());
							ps4.setInt(6, driid);
							if (ps4.executeUpdate() != 0) {
								SendSMSUtil
										.getInstance()
										.sendSMS(
												userTel,
												URLEncoder
														.encode("您的代驾已经完成，此次代驾费用为"
																+ total
																+ "元，请进入“预约订单”-“计价器”，点击“支付”，选择相应的支付方式，请于20分钟内完成支付，如有疑问请联系：4008200972，邦尼驾驶祝您生活愉快~",
																"gbk"));
								if (null == rs2.getString(6)
										&& null == rs2.getString(7)) {
									PreparedStatement mPs = con
											.prepareStatement(sql_update_pos);
									mPs.setInt(1, formid);
									if (mPs.executeUpdate() == 0)
										return 9;// 地址，日期更改失败
								}
								con.commit();
								return System.currentTimeMillis();
							}
							return 10;// 订单修改失败
						}
						return 11;// 不存在对应opp
					}
					return 4;
				}
				return 6;
			}
			return 4;
			// if ("5".equals(opp)) {// 取消订单
			// DBUtil.getInstance().closeConnection(con);
			// return System.currentTimeMillis();
			// }
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println(e.toString());
			return 3 + e.getErrorCode();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return 8;
		} finally {
			DBUtil.getInstance().closeConnection(con);
		}
	}

	public int updateTaximeter(int driid, String sm, String sop, String sowp,
			String sowt, int up, int period, String total, int state) {
		String sql_update = "UPDATE t_djpd SET sm=?,sop=?,sowp=?,sowt=?,up=?,period=?,taxi_state=?,total=? WHERE dri_id = ? AND state < 6 AND state > 2";
		Connection con = DBUtil.getInstance().openConnection();
		try {
			con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			con.setAutoCommit(false);
			PreparedStatement ps = con.prepareStatement(sql_queryByDriid);
			ps.setInt(1, driid);
			ResultSet rs = ps.executeQuery();
			int mState;
			if (rs.next() && ((mState = rs.getInt(1)) == 3 || mState == 4)) {
				PreparedStatement ps1 = con.prepareStatement(sql_update);
				ps1.setString(1, sm);
				ps1.setString(2, sop);
				ps1.setString(3, sowp);
				ps1.setString(4, sowt);
				ps1.setInt(5, up);
				ps1.setInt(6, period);
				ps1.setInt(7, state);
				ps1.setString(8, total);
				ps1.setInt(9, driid);
				if (ps1.executeUpdate() == 1) {
					con.commit();
					return 0;
				}
				return 2;
			}
			return 1;
		} catch (SQLException e) {
			e.printStackTrace();
			return 3;
		} finally {
			DBUtil.getInstance().closeConnection(con);
		}
	}

	public Taximeter getTaximeter(int userid, int formid) {
		String sql_query = "SELECT t_djpd.state,t_djpd.sm,t_djpd.sop,t_djpd.sowp,t_djpd.sowt,t_djpd.up,t_djpd.period,t_djpd.total,t_djpd.taxi_state FROM t_djpd,t_hy WHERE t_djpd.id=? AND t_djpd.user_id = ?";
		Connection con = DBUtil.getInstance().openConnection();
		try {
			con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			PreparedStatement ps = con.prepareStatement(sql_query);
			ps.setInt(1, formid);
			ps.setInt(2, userid);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				Taximeter t = new Taximeter(rs.getString(1) + "",
						rs.getString(2) + "", rs.getString(3) + "",
						rs.getString(4) + "", rs.getString(5) + "",
						rs.getString(6) + "", rs.getString(7) + "",
						rs.getString(8) + "", rs.getString(9) + "");
				DBUtil.getInstance().closeConnection(con);
				return t;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		DBUtil.getInstance().closeConnection(con);
		return new Taximeter("", "", "", "", "", "", "", "", "");
	}

	private String encryption(int param) {
		param *= KEY;
		return Integer.toHexString(param);
	}

	private double getManageProfit(double param, int mdid) {
		double mParam = param * 0.04d;
		if (mdid == 7)
			mParam = param * 0.15d;
		return FormatUtil.getFormatDouble(3, mParam);
	}

	private double getTax(double total) {
		if (total < 20)
			return 0;
		if (total >= 20 && total < 50)
			return 0.1;
		if (total >= 50 && total < 100)
			return 0.15;
		return 0.2;
	}
}
